package com.educate.common.handler;

import cn.hutool.json.JSONUtil;
import com.educate.common.api.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yjj
 * @date 2021/11/7
 * @description: 登录失败处理器
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        String errorInfo = e.getMessage();
        if("Bad credentials".equals(errorInfo)){
            errorInfo = "账号或密码错误!";
        }
        outputStream.write(JSONUtil.toJsonStr(Result.failed(errorInfo)).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}
